/**工具集**/
var comfirmLabelTypes = [ 
	{'yes':'yes', 'no':'no'}, 
	{'yes':'是', 'no':'否'},
	{'yes':'确认', 'no':'取消'},
	{'yes':'确定', 'no':'取消'}
];

var alertLabelTypes = [
	{'ok' : 'ok'},
	{'ok' : 'OK'},
	{'ok' : '好'},
	{'ok' : '是'},
	{'ok' : '确定'}
]

var tableModel = (function () {
    return{
        getHeight : function () {
            return $(window).height() - $('.content-header').outerHeight(true);
        },
        getState : function (value,row,index) {
            return value==1 ? "启用" : "禁用";
        }
    }
})();

/**
 * 确认弹出框，用于弹出确认消息，按钮为yes/no两个，文字自定义
 * @param {} msg 弹出框内容
 * @param {} dtitle 弹出框标题
 * @param {} btnLabelType 按钮类型 默认为 是/否
 * @param {} okAction ok按钮的回调函数
 */
function customConfirmDialog(msg, dtitle, btnLabelType, okAction){
	if(btnLabelType == undefined || btnLabelType == null) btnLabelType = 1;
	BootstrapDialog.show({
		type : BootstrapDialog.TYPE_PRIMARY,
		message: msg,
		cssClass: "customDialog",
		title: dtitle,
		buttons: [{
			label: comfirmLabelTypes[btnLabelType].no,
			cssClass: 'btn-inverse',
			action: function(dialogItself){
				dialogItself.close();
			}
		},{
			label: comfirmLabelTypes[btnLabelType].yes,
			cssClass: 'btn-primary',
			action: okAction
		}]
	});
}

/**
 * 提示弹出框，用于弹出提示消息，按钮为ok一个，文字自定义
 * @param {} msg 弹出框内容
 * @param {} dtitle 弹出框标题
 * @param {} btnLabelType 按钮类型 默认为 确定
 * @param {} okAction ok按钮的回调函数
 */
function customAlertDialog(msg, dtitle, btnLabelType, okAction){
	if(btnLabelType == undefined || btnLabelType == null) btnLabelType = 4;
	if(okAction == undefined || okAction == null){
		okAction = function(dialogItself){
			dialogItself.close();
		}
	}
	BootstrapDialog.show({
		type : BootstrapDialog.TYPE_PRIMARY,
		title: dtitle,
		cssClass: "customDialog",
		message: msg,
		buttons:[{
			label: alertLabelTypes[btnLabelType].ok,
			action: okAction,
			cssClass: "btn-primary"
		}]
	});
}

/**
 * 提示弹出框，用于弹出提示消息，按钮为ok一个，文字自定义，该弹出框只能通过确认按钮关闭
 * @param {} msg 弹出框内容
 * @param {} dtitle 弹出框标题
 * @param {} btnLabelType 按钮类型 默认为 确定
 * @param {} okAction ok按钮的回调函数
 */
function unclosableAlertDialog(msg, dtitle, btnLabelType, okAction){
	if(btnLabelType == undefined || btnLabelType == null) btnLabelType = 4;
	if(okAction == undefined || okAction == null){
		okAction = function(dialogItself){
			dialogItself.close();
		}
	}
	BootstrapDialog.show({
		title: dtitle,
		cssClass: "customDialog",
		message: msg,
		closable: false,
		closeByBackdrop: false,
        closeByKeyboard: false,
		buttons:[{
			label: alertLabelTypes[btnLabelType].ok,
			action: okAction,
			cssClass: "btn-primary"
		}]
	});
}

/**
 * 内容弹出框，用于弹出页面内简单的div内容，只用于显示，所有操作在div内实现
 * 注意：因为弹出框内的id与页面内实际id一致，所以有必要时需将div字符串内的id进行转换后再传入
 * @param {} msg div内容字符串，通常为页面div的html()方法获取并处理后的结果
 * @param {} dtitle 弹出框标题
 */
function customPagedivDialog(msg, dtitle, size){
	BootstrapDialog.show({
		type : BootstrapDialog.TYPE_PRIMARY,
		title: dtitle,
		draggable: true,
		closeByBackdrop: false,
		closeByKeyboard: false,
		size: size || BootstrapDialog.SIZE_WIDE,
		cssClass: "customDialog",
		nl2br: false,
		message: msg
	});
}

/**
 * 内容弹出框，用于弹出页面内简单的div内容，通过远程URL填充div
 * @param {} url 远程URL
 * @param {} dtitle 弹出框标题
 */
function customRemoteUrlDialog(dtitle,url, size){
	BootstrapDialog.show({
		type : BootstrapDialog.TYPE_PRIMARY,
		title: dtitle,
		draggable: true,
		closeByBackdrop: false,
		closeByKeyboard: false,
		size: size || BootstrapDialog.SIZE_WIDE,
		nl2br: false,
		cssClass: "customDialog",
		message : function(dialog) {
			var $message = $('<div></div>');
			var pageToLoad = dialog.getData('pageToLoad');
			$message.load(pageToLoad);
			return $message;
		},
		data : {
			'pageToLoad' : path + url
		}
	});
}

function customTimeOutDialog(dtitle,message,type,timeOut,callback){
	var dialog = BootstrapDialog.show({
		type : type || BootstrapDialog.TYPE_SUCCESS,
		size: BootstrapDialog.SIZE_SMALL,
		title : dtitle,
		message : message
	});
	setTimeout(function() {
		dialog.close();
		if(callback && (typeof callback == 'function')){
			callback();
		}
	}, timeOut);
}

function closeAllDialog(){
	BootstrapDialog.closeAll();
}

/**
 * 需要返回的跳转，将需要返回的页面的地址包装后传入，在跳转到的页面进行返回时调用redirectCallback即可
 * @param {} headerUrl 需要跳转到的页面的URL，包含该页面需要的参数
 * @param {} preUrl 当前页面的URL，以及回调时需要的参数，如果需要回调时传回变量，用{}标识，里面的内容为跳转到的页面的操作结果对象的属性名
 */
function redirectCall(headerUrl, preUrl){
	window.location.href = path+headerUrl + ((headerUrl.indexOf("?") == -1) ? "?" : "&") + "preUrl=" + encodeURIComponent(preUrl);
}

/**
 * 跳转返回前一个页面，在URL中存在preUrl参数时，需要进行回调，如果回调需要额外传变量参数，需要把操作结果的对象传入到此函数内
 * @param {} params 操作结果的对象，回调有额外参数时使用，需要包含preUrl的{}中定义的属性名及其对应值
 * @return {Boolean} 如没有进行跳转，返回false
 */
function redirectCallback(params){
	var preUrl = $.getQueryParam().preUrl;
	if(preUrl){
		preUrl = decodeURIComponent(preUrl);
		if(params){
			preUrl = preUrl.replace(/\{(.+?)\}/g,function(m, i){
				return params[i] == null ? '' : params[i];
			});
		}
		if(preUrl.indexOf("preUrl") > 0){
			var position = preUrl.indexOf("preUrl")+7;
			preUrl= preUrl.substr(0,position) + encodeURIComponent(preUrl.substr(position));
		}
		window.location.href = path+preUrl;
		return false;
	}
}

/**
 * 根据页面上元素配置的组，进行元素切换（类似tab页功能）
 * @param {} parentContainer 父容器的ID，一般指外层div的ID
 * @param {} group 元素上配置的group属性，指一级分组，必传
 * @param {} subgroup 元素上配置的subgroup属性，指二级分组，可不传，不传时进行单一层级元素切换
 * @param {} tag 元素标签，默认是div
 */
function radioSelectContent(parentContainer, group, subgroup, tag){
	if(group==null || group==undefined || subgroup==null || subgroup==undefined){
		return;
	}
	var selectorShow = "";
	var selectorHide = "";
	if(parentContainer!=null && parentContainer!=undefined){
		selectorShow += "#"+parentContainer+" ";
	}
	if(tag==null || tag==undefined){
		tag='div';
	}
	selectorShow += tag;
	selectorShow += "[group="+group+"]";
	selectorHide = selectorShow + "[subgroup!="+subgroup+"]";
	selectorShow += "[subgroup="+subgroup+"]";
	
	$(selectorShow).each(function(){
		$(this).show();
	});
	
	$(selectorHide).each(function(){
		$(this).hide();
	});
}

/**
 * 根据页面上元素配置的组，进行元素切换（类似tab页功能），切换时将当前选中的置为选中状态，其他的置为非选中状态
 * @param {} parentContainer 父容器的ID，一般指外层div的ID
 * @param {} group 元素上配置的group属性，指一级分组，必传
 * @param {} selectId 选中的元素的ID
 * @param {} tag 元素标签，默认是div
 */
function radioSelectPanel(parentContainer, group, selectId, tag){
	if(group==null || group==undefined || selectId==null || selectId==undefined){
		return;
	}
	if(tag==null || tag==undefined){
		tag='div';
	}
	var selectorShow = "";
	var selectorHide = "";
	if(parentContainer!=null && parentContainer!=undefined){
		selectorShow += "#"+parentContainer+" ";
	}
	selectorShow += tag;
	selectorShow += "[group="+group+"]";
	selectorHide = selectorShow + "[id!="+selectId+"]";
	selectorShow += "[id="+selectId+"]";
	
	$(selectorShow).each(function(){
		$(this).addClass('selected');
	});
	
	$(selectorHide).each(function(){
		$(this).removeClass('selected');
	});
}

/**
 * 功能:callback生成，用于弹出确认提示框，点击确认后，提交数据，根据返回值显示信息并刷新/跳转页面
 * @param {} uri 确认后请求服务的地址
 * @param {} query 向后台请求的查询参数
 * @param {} method 请求方法执行的动作 post/put/delete/get
 * @param {} param 做post/put提交时，上传的内容
 * @param {} callback 弹出结果提示框后，2秒自动执行的方法，默认为刷新当前页面
 * @param {} check 检验结果是否正确的标准，默认为result_code == 1
 */
function createRefreshCallback(uri, query, method, param, callback, check){
	return function(dialog) {
		var request = !!query ? $.getApiClient(uri).setQuery(query) : $.getApiClient(uri);
		var response = null;
		switch(method){
		case 'get': response = request.get(); break;
		case 'put': response = request.put(param); break;
		case 'del': response = request.del(); break;
		case 'post': response = request.post(param); break;
		}
		response.done(function(data){
			var resultStatus = !check ? data.result_code == 1 : data[check];
			var resultStatusStr = resultStatus ? "成功" : "失败";
			customAlertDialog(data.result_msg, "操作"+resultStatusStr);
			if(!callback) callback = function(){window.location.reload();}
			resultStatus && setTimeout(callback, 2000);
		});
		dialog.close();
	};
}

function timeFormatter(value) {
	return value;
//	return time=$.dateFormat(value, "yyyy-MM-dd HH:mm:ss");
}

function dateFormatter(value) {
	return value;
//	return date=$.dateFormat(value, "yyyy-MM-dd");
}

function heredoc(fn) {
    return fn.toString().split('\n').slice(1,-1).join('\n') + '\n'
}

function transcode(value, row, rowindex) {
	if (!this.formatterArgs) {
		return value;
	}
	return window[this.formatterArgs][value] || null;
}

function getTreeData(treeNode) {
	var properties = [ 'title', 'description', 'type' ];

	var data = {};
	$.each(treeNode, function(key, value) {
		if ($.inArray(key, properties) > -1)
			data[key] = value;
	});
	return data;
}

function getTreeJson(treeId) {
	var getTreeNodeJson = function(treeNode) {
		var treeData = getTreeData(treeNode);

		if (treeNode.children != null && treeNode.children.length > 0) {
			treeData.properties = {};
			$.each(treeNode.children, function(index, child) {
				var childData = getTreeNodeJson(child);
				treeData.properties[childData.title] = childData;
				delete childData.title;
			});
		}
		return treeData;
	}

	var rootData = getTreeNodeJson($.fn.zTree.getZTreeObj(treeId).getNodes()[0]);
	delete rootData.title;
	return rootData;
}

function bindDataForTree(treeId, treeData) {
	var zTree = $.fn.zTree.getZTreeObj(treeId);
	var renderChildren = function(treeNode, childData) {
		if (!childData)
			return;
		$.each(childData, function(key, value) {
			var childNum = 0;
			if (treeNode.children != null) {
				childNum = treeNode.children.length;
			}
			var nodeId = treeNode.id + (childNum + 1);
			var nodes = zTree.addNodes(treeNode, $.extend({
				"id" : nodeId,
				"grade" : parseInt(treeNode.grade) + 1,
				"parent_id" : treeNode.id,
				"title" : key
			}, value));
			renderChildren(nodes[0], value.properties);
		});
	}
	var root = zTree.getNodes()[0];
	renderChildren(root, treeData);
}

function setForm(data){
	for (var countryObj in data){
		if(document.getElementById(countryObj) != null){
			if(data[countryObj] == null || data[countryObj] == "null") data[countryObj] = "";
			$("#"+countryObj).text(data[countryObj]);
		}
	}
}

function setFormValue(data){
	for (var countryObj in data){
		if(document.getElementById(countryObj) != null){
			if($("#"+countryObj).attr("multiple")){
				/*修改属性为null或undefined时js脚本错误*/
				$("#"+countryObj).multipleSelect('setSelects',(data[countryObj]||'').split(","));
			}else{
				$("#"+countryObj).val(data[countryObj]);
			}
		}
	}
}

/*
*功能:获得选中控件的值
*/
function getCheckValue(name){
	var id = "";
	$("input[name='"+name+"']:checked").each(function (){
		id=this.id; 
	});
	return $("#"+id).val();
}

/**
 * 根据数据字典生成下拉框
 * groupcode:数据字典组code
 * selectElid:下拉框ID
 * defaultValue:默认选中值
 */
function genDictSelect(groupcode,selectElid,defaultValue,extendItem){
	var selectInfo=[];
	if(extendItem){
		selectInfo.push(extendItem);
	}
	var groupInfo = $.grep(sysDict,function(item,index){
		return item['group_code'] == groupcode;
	})
	if(groupInfo[0]){
		$.each(groupInfo[0].datas,function(index,item){
			selectInfo.push({code:item.item_code,value:item.item_name})
		})
	}
	multipleSelectData(selectElid,selectInfo);
	$('#'+selectElid).multipleSelect({
		width : '100%',
		single : true
	});
	$('#'+selectElid).multipleSelect("setSelects",[defaultValue]);
}

/**
 * 根据数据字典生成转换表格内容参数map
 * groupcode:数据字典组code
 */
function getTransParam(groupcode){
	var dictInfo=[];
	var groupInfo = $.grep(sysDict,function(item,index){
		return item['group_code'] == groupcode;
	})
	$.each(groupInfo[0].datas,function(index,item){
		dictInfo.push({code:item.item_code,value:item.item_name})
	})
	return $.getMapByArray(dictInfo, {valueAttr : "code", displayAttr : "value"});
}

(function($) {
	$.extend({
		getQueryParam : function() {
			var url = location.search; // 获取url中"?"符后的字串
			if (url == "") {
				return {};
			}

			if (url.charAt(0) == '?') {
				url = url.substr(1);
			}

			var queryParams = {};
			$.each(url.split('&'), function(i, param) {
				param = param.split('=');
				queryParams[param[0]] = (param.length == 1 ? '' : param[1]);
			});

			return queryParams;
		},
		download : function(url, data, method){
		    if( url ){
		    	var inputs = '';
		    	if(data){
		    		// data 是 string 或者 array/object
			        data = typeof data == 'string' ? data : $.param(data);     
			        // 把参数组装成 form的  input
			        $.each(data.split('&'), function(){
			            var pair = this.split('=');
			            inputs+='<input type="hidden" name="'+ pair[0] +'" value="'+ pair[1] +'" />'; 
			        }); 
		    	}
		        // request发送请求
		        $('<form action="'+path+'/api/'+url +'" method="'+ (method||'get') +'">'+inputs+'</form>')
		        .appendTo('body').submit().remove();
		    }
		},
		getMapByArray : function(array, data) {
			if (!data) {
				data = {
					valueAttr : "value",
					displayAttr : "name"
				};
			}

			// 判断是否多值
			var all = data.displayAttr == '';
			var map = {};
			$.each(array, function(i, row) {
				map[row[data.valueAttr]] = all ? row : row[data.displayAttr];
			});
			return map;
		},
		goBack : function() {
			if (reloadUrl) {
				location.href = reloadUrl;
			} else {
				history.back();
			}
		},
		dateFormat : function(inValue, datePattern, data) {
			if (!inValue || inValue == "")
				return "";
			var date, retV = datePattern || "yyyy-MM-dd";
			!data && (data = {
				dataType : "date"
			});

			if (data["dataType"] == "string" || data["dataType"] == "text") {
				var valueFormat = data["valueFormat"] || retV;
				var date = $.dateParser(inValue, valueFormat);
			} else {
				var date = new Date(Number(inValue));
			}
			return $.dateFormatToString(date, retV);
		},
		/**
		 * @summary: 日期转换，将一定格式的字符串转换为日期对象
		 * @param: {string} str 要转换的日期字符串
		 * @param: {string} format 字符串符合的格式
		 * @return : {date} 转换后的日期对象
		 * @example: |<script> | var value = "19810615"; | var datePattern =
		 *           "yyyyMMdd" | alert(unieap.dateParser(value,datePattern)); |</script>
		 */
		dateParser : function(str, format) {
			var now = new Date();
			if (str.lastIndexOf('am') > -1) {
				format = format + ' am';
			}

			if (str.lastIndexOf('pm') > -1) {
				format = format + ' pm';
			}

			if (str.length !== format.length) {
				return now;
			}
			var sub = function(s, f1) {
				var rtv = -1;
				var index = format.indexOf(f1);
				if (index != -1) {
					rtv = parseInt(s.substr(index, f1.length), 10);
				}
				return rtv;
			}
			var year = sub(str, "yyyy");
			(year == -1) && (year = now.getYear());
			var month = sub(str, "MM");
			(month == -1) && (month = now.getMonth() + 1);
			var date = sub(str, "dd");
			(date == -1) && (date = 1);// 如果没有dd，则日期选中的每月1号

			// 处理12小时和24小时制度
			var hour = -1;
			if (sub(str, 'hh') != -1) { // 如果是12进制
				hour = sub(str, 'hh');
				if (str.indexOf('pm') != -1) {
					// 12进制12:12 pm转换为24进制应该还是12:12
					// 1:12pm 应该是13:12
					hour = (hour == 12) ? 12 : hour + 12;

				} else if (str.indexOf('am')) {
					// 12进制12:12am转换为24进制应该是00:12
					hour = (hour == 12) ? 0 : hour;
				}
			} else if (sub(str, 'HH') != -1) {
				hour = sub(str, 'HH');
			}
			(hour == -1) && (hour = 0);
			var minute = sub(str, "mm");
			(minute == -1) && (minute = 0);
			var second = sub(str, "ss");
			(second == -1) && (second = 0);
			var d = new Date(year, month - 1, date, hour, minute, second);
			if (d == "NaN") {
				return now;
			}
			return d;
		},

		/**
		 * @summary: 日期转换，将日期对象转换为一定格式的字符串
		 * @param ：
		 *            {date} date 要转换的日期对象
		 * @param ：
		 *            {string} retV 要转换成的格式
		 * @return： {string} 转换后的日期格式
		 * @example: |<script> | var date = new Date(2008,8,8,12,12,30); | var
		 *           retV = "yyyy-MM-dd" |
		 *           alert(unieap.dateFormatToString(date,retV)); |</script>
		 */
		dateFormatToString : function(date, retV) {
			// parse year
			if (retV.indexOf("yyyy") != -1) {
				retV = retV.replace(/yyyy/gi, date.getFullYear());
			}

			// parse month
			if (retV.indexOf("MM") != -1) {
				var m = date.getMonth() + 1;
				m = m < 10 ? "0" + m : m;
				retV = retV.replace(/MM/g, m);
			}

			// parse day
			if (retV.indexOf("dd") != -1) {
				var d = date.getDate();
				d = d < 10 ? "0" + d : d;
				retV = retV.replace(/dd/g, d);
			}

			// parse hour
			if (retV.indexOf('hh') != -1) {
				var h = date.getHours();
				if (h >= 12) {
					retV = retV + " pm"
					h = (h == 12) ? 12 : h - 12; // 如果当前时间是12:12,转换成12进制为12:12
					// pm
				} else {
					retV = retV + " am"
					h = (h == 0) ? 12 : h; // 如果当前时间是00:12,转换成12进制为12:12
					// am
				}
				h = h < 10 ? "0" + h : h;
				retV = retV.replace(/hh/g, h);
			} else if (retV.indexOf('HH') != -1) {
				var h = date.getHours();
				h = h < 10 ? "0" + h : h;
				retV = retV.replace(/HH/g, h);
			}

			// parse minute
			if (retV.indexOf("mm") != -1) {
				var mm = date.getMinutes();
				mm = mm < 10 ? "0" + mm : mm;
				retV = retV.replace(/mm/g, mm);
			}
			// parse second
			if (retV.indexOf("ss") != -1) {
				var s = date.getSeconds();
				s = s < 10 ? "0" + s : s;
				retV = retV.replace(/ss/g, s);
			}
			// week
			if (retV.indexOf("w") != -1) {
				retV = retV.replace(/w/g, "0");
			}
			return retV;
		},
		getCurrentDateTime : function() {
			return $.dateFormatToString(new Date(), 'yyyyMMddHHmmss');
		},
		dateAdd : function(date,strInterval, Number){
			var dtTmp = date;
			switch (strInterval) {
			case 'second':
			case 's':
				return new Date(Date.parse(dtTmp) + (1000 * Number));
			case 'minute':
			case 'n':
				return new Date(Date.parse(dtTmp) + (60000 * Number));
			case 'hour':
			case 'h':
				return new Date(Date.parse(dtTmp) + (3600000 * Number));
			case 'day':
			case 'd':
				return new Date(Date.parse(dtTmp) + (86400000 * Number));
			case 'week':
			case 'w':
				return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
			case 'month':
			case 'm':
				return new Date(dtTmp.getFullYear(), (dtTmp.getMonth())
						+ Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp
						.getMinutes(), dtTmp.getSeconds());
			case 'year':
			case 'y':
				return new Date((dtTmp.getFullYear() + Number), dtTmp
						.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp
						.getMinutes(), dtTmp.getSeconds());
			}  
		},
		ifPresent : function(map, filed, defaultValue) {
			if (map == null) {
				return defaultValue;
			}
			return map[filed];
		}
	});
})(jQuery);